import qs from 'qs';

const APP = {
    data() {
        return {
            order: 0,
            questionData: {},
            myAnswer: -1,
            myResults: [],
            text: []
        }
    },
    template: `
    <div>
        <div v-if="myResults.length>0">
        <h1>考试结果及答案</h1>
        <br/>
            <div v-for="item in myResults"
            :key="item"
            >
                <h2>题目：{{ item.qId }}</h2>
                <p>{{ item.question }}</p>
                <span>我的答案：{{ item.myAnswer }}&nbsp;&nbsp;</span>
                <span>正确答案：{{ item.rightAnswer }}&nbsp;&nbsp;</span>
                <span>结果：{{ item.isTrue }}</span>
                <br/>
            </div>
        </div>
        <div v-else>
            <h1>编号:{{ questionData.id }}</h1>
            <p>{{ questionData.question }}</p>
            <div>
                <button
                    v-for="(item,index) in questionData.items"
                    :key="item"
                    @click="selectAnswer(index)"
                >{{ item }}</button>
            </div>
        </div>
    </div>
    `,
    // 生命周期函数 mounted
    // 在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作。
    mounted() {
        this.getQuestion(this.order);
    },
    watch: {
        order(newOrder, oldOrder) {
            this.uploadAnswer(oldOrder, this.myAnswer);
            this.getQuestion(newOrder);
        }
    },
    methods: {
        getQuestion(order) {
            axios.post('http://localhost:8090/getQuestion', qs.stringify({
                order
            })).then(res => {
                const result = res.data;
                if (result.errorCode) {
                    this.myResults = result.data;
                    return;
                } else {
                    this.questionData = result.data;
                    console.log(res)
                }
            })
        },
        uploadAnswer(order, myAnswer) {
            axios.post('http://localhost:8090/uploadAnswer', qs.stringify({
                order,
                myAnswer
            }))
        },
        selectAnswer(index) {
            this.myAnswer = index;
            this.order += 1;
        }
    }
}

const vm = Vue.createApp(APP).mount('#app');



